"""
数据管理模块
Data management module for saving and loading sensor data
"""

import json
import os
import logging
from config import DATA_CONFIG

logger = logging.getLogger(__name__)

class DataManager:
    def __init__(self):
        self.save_file = DATA_CONFIG['save_file']
        self.max_records = DATA_CONFIG['max_records']
        
    def load_existing_data(self):
        """加载现有数据"""
        sensor_records = []
        if os.path.exists(self.save_file):
            try:
                with open(self.save_file, 'r', encoding='utf-8') as f:
                    sensor_records = json.load(f)
                    if not isinstance(sensor_records, list):
                        sensor_records = []
                logger.info(f"加载了 {len(sensor_records)} 条历史记录")
            except Exception as e:
                logger.error(f"加载历史数据失败: {e}")
                sensor_records = []
        return sensor_records
    
    def save_sensor_data(self, sensor_records, new_data):
        """保存传感器数据"""
        if new_data is None:
            return sensor_records
        
        # 添加到记录列表
        sensor_records.append(new_data)
        
        # 限制记录数量
        if len(sensor_records) > self.max_records:
            sensor_records = sensor_records[-self.max_records:]
        
        # 保存所有数据到文件
        try:
            with open(self.save_file, 'w', encoding='utf-8') as f:
                json.dump(sensor_records, f, indent=2, ensure_ascii=False)
            logger.info(f"数据保存成功: {new_data}")
        except Exception as e:
            logger.error(f"数据保存失败: {e}")
        
        return sensor_records
